package com.geek2.springbootdemo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().disable();
        http.authorizeRequests()
                .antMatchers("/").permitAll()
                .antMatchers("/main").hasRole("aa")
                .antMatchers("/member-*").hasRole("bb");
//                .anyRequest().authenticated(); // 用户访问其它URL都必须认证后访问

        /*
        * formLogin()           没有授权,默认回到登陆界面
        * loginPage(/toLogin)   设置登录页面访问地址
        * loginProcessingUrl    设置登录页提交地址
        * */
        http.formLogin().loginPage("/toLogin").loginProcessingUrl("/login");
//        http.csrf().disable();
        //启用注销功能，（需要提供一个action为/logout的form）并设置注销后访问的url，这里注销后跳转到首页
        http.logout().logoutUrl("/toLogout").logoutSuccessUrl("/");
        //启用rememberMe功能，将用户信息保存在cookie中
        http.rememberMe();
    }

/*
    @Override
    public void configure(WebSecurity web) throws Exception {
        //静态资源过滤
        web.ignoring().antMatchers("/css/**", "/js/**", "/images/**");
    }
*/

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("1111").password(new BCryptPasswordEncoder().encode("12345")).roles("aa", "bb", "cc")
                .and()
                .withUser("2222").password(new BCryptPasswordEncoder().encode("12345")).roles("bb")
                .and()
                .withUser("3333").password(new BCryptPasswordEncoder().encode("12345")).roles("admin");
    }
}
